<?php

class Mageex_AdvanceSeo_Helper_Data extends Mage_Core_Helper_Abstract
{
	protected $_storeId;
	
	public function __construct()
	{
			$this->_storeId = Mage::app()->getStore()->getId();
	}
	public function stringReplace($value)
	{
		$charaterA = '#(à|ả|ã|á|ạ|ă|ằ|ẳ|ẵ|ắ|ặ|â|ầ|ẩ|ẫ|ấ|ậ)#imsU';
		$repleceCharaterA = 'a';
		$value = preg_replace($charaterA,$repleceCharaterA,$value);
		
		$charaterD = '#(đ)#imsU';
		$replaceCharaterD = 'd';
		$value = preg_replace($charaterD,$replaceCharaterD,$value);
		
		$charaterE = '#(è|ẻ|ẽ|é|ẹ|ê|ề|ể|ễ|ế|ệ)#imsU';
		$replaceCharaterE = 'e';
		$value = preg_replace($charaterE,$replaceCharaterE,$value);
	
		$charaterI = '#(ì|ỉ|ĩ|í|ị)#imsU';
		$replaceCharaterI = 'i';
		$value = preg_replace($charaterI,$replaceCharaterI,$value);
		
		$charaterO = '#(ò|ỏ|õ|ó|ọ|ô|ồ|ổ|ỗ|ố|ộ|ơ|ờ|ở|ỡ|ớ|ợ)#imsU';
		$replaceCharaterO = 'o';
		$value = preg_replace($charaterO,$replaceCharaterO,$value);
				
		$charaterU = '#(ù|ủ|ũ|ú|ụ|ư|ừ|ử|ữ|ứ|ự)#imsU';
		$replaceCharaterU = 'u';
		$value = preg_replace($charaterU,$replaceCharaterU,$value);
		
		$charaterY = '#(ỳ|ỷ|ỹ|ý)#imsU';
		$replaceCharaterY = 'y';
		$value = preg_replace($charaterY,$replaceCharaterY,$value);
		
		return $value;
	}
	public function getArrFromTemplate($string)
	{
		preg_match_all('/((\{\w*\}|(\{\w+\|\w+\})))/',$string,$matches,PREG_OFFSET_CAPTURE);
		return $matches[0];
	}
	public function stringConvert($string)
	{
		$len = strlen($string);
		for ($i=0; $i<$len; $i++){
			if($string[$i] == '"' || $string[$i] == '/'){
				$string[$i] = '-';
			}
		}
		$string = preg_replace('#(\s+)#', '-', $string);	
		$string = $this->stringReplace($string);
		return strtolower($string);
	}
	public function getSuffix()
	{
		$suffix = '.html';
		if(Mage::getStoreConfig('catalog/seo/category_url_suffix', $this->_storeId)!='' && Mage::getStoreConfig('catalog/seo/category_url_suffix')){
			$suffix = Mage::getStoreConfig('catalog/seo/category_url_suffix', $this->_storeId);
		}
		return $suffix;
	}
	public function getDataToArray($str, $separate){
		return explode($separate, $str);
	}
	
	public function limitContentByWord($str, $limit){
		$str = trim($str);
        $count=1;
        for($i=0; $i<strlen($str); $i++){
        	if(($str[$i]==" ") && ($str[$i+1] != " ")){
                $count++;
            }
            if($count == ($limit+1)){
                    $str = substr($str,0, $i);
            }
        }
       	return $str;
	}
	
	public function getStrFromTemplate($arrAttribute, $arrCode, $str)
    {
    	for ($i=0; $i<count($arrAttribute); $i++){
    		$arrTemp = $arrAttribute[$i];
    		$code = str_replace('{','',$arrTemp[0]);
			
			
			
    		$code = str_replace('}','',$code);
    		$code =  explode('|', $code);
			
    		if(count($code)>1){
    			for ($j=0; $j<count($code); $j++){
    				if(!empty($arrCode[$code[$j]])){

						if($code[$j] == 'name') {
							$str = str_replace('{'. $code[$j] .'|'.$code[$j+1].'}', $arrCode[$code[$j]].' ', $str);
						}else{
							$str = str_replace('{'. $code[$j] .'|'.$code[$j+1].'}', $arrCode[$code[$j]], $str);
						}
    					break;
    				}else{
    					$str = str_replace('{'. $code[$j] .'|'.$code[$j+1].'}', ' ', $str);
    				}
    			}
    		}else{
    			if(!empty($code[0])){
					if($code[0] == 'name') {
						$str = str_replace('{'. $code[0] .'}', $arrCode[$code[0]].' ', $str);
					}else{
						$str = str_replace('{'. $code[0] .'}',$arrCode[$code[0]], $str);
					}
    			}else{
					if($code[0] == 'name') {
						$str = str_replace('{'. $code[0] .'}', $arrCode[$code[0]].' ', $str);
					}else{
						$str = str_replace('{'. $code[0] .'}',$arrCode[$code[0]], $str);	
					}
    				
    			}
    		}
    	}
		
		//$st = str_replace('-', ' ', $str);
    	return $str;    	
    }
	
	public function splitTwoWords($arrWord){
        $str = '';
        for($i=0; $i<count($arrWord); $i++){
            if($i%2==0 && $i>0){
				$str .= ', ' . $arrWord[$i];
			}else{
				$str .= ' '. $arrWord[$i];
			}
        }
        return $str;
    }
	public function getData($strconfig, $separate=null)
	{
		$str = Mage::getStoreConfig($strconfig, $this->_storeId);
		if($separate != null){
			$result = explode(',', $str);
		}else{
			$result = $str;	
		}
		return $result;
	}
	public function getNameConverted($arrElement)
	{
		for($i=0; $i<count($arrElement); $i++){	
			$arrElement[$i]	= str_replace(Mage::helper('advanceseo/data')->getSuffix(), '', $arrElement[$i]);
			$arrElement[$i] = ucfirst($arrElement[$i]);
		}
		return implode(' ', $arrElement);
	}
	
	public function getCurrentUrl()
	{
		 $protocol 	= $_SERVER['HTTPS'] ? "https" : "http";
		 $baseUrl 	= $protocol . "://" . $_SERVER['HTTP_HOST'];
		 $strUri 	= trim($_SERVER['REQUEST_URI'], '/');
		 $arrUri 	= explode('/',$strUri);
			
		 foreach($arrUri as $uri){
			$baseUrl .= '/'.str_replace(Mage::helper('advanceseo/data')->getSuffix(), '', $uri);
			if($uri==Mage::helper('advanceseo/config')->getPathFilter()){
				 break;
			}
		 }
		 if(!in_array(Mage::helper('advanceseo/config')->getPathFilter(),$arrUri)){
			 $baseUrl.='/'.Mage::helper('advanceseo/config')->getPathFilter();
		 }
		//echo $baseUrl;
		return $baseUrl;
	 }
	public function getFileNameToArr($dir,$excludeWord, $parentName,$removeExten=true,$extension=''){
		$dh = opendir($dir);
		if($dh==false){return false;}
		$arr = array();
		while($file = readdir($dh)){
			if($file !='.' && $file !='..'){
				if(preg_match('/'.$parentName.'/i', $file) && !preg_match('/'.$excludeWord.'/i', $file)){
					if($removeExten==true)
						$arr[] = str_replace($extension,"",trim($file));
					else
						$arr[] = trim($file);
				}
			}	
		}
		closedir($dh);
		return $arr;
	}
	public function removeHtmlTag($str){
		return preg_replace('/<(.*?)>/i', ' ', $str);
	}
	public function getProductTitle($product) {
	
		//Rewrite meta
		$collection = Mage::getResourceModel('eav/entity_attribute_collection')
						->setEntityTypeFilter( Mage::getModel('eav/entity')->setType('catalog_product')->getTypeId() )
						->addFilter("is_visible", 1)
						->addFilter("is_filterable", 1);
						
		$arrCode = array();		
		
		foreach($collection->getItems() as $col) {
			$arrCode[] = $col->getAttributeCode();
		}
		
		$arrCode[] = 'name';
		$arrCode[] = 'supplier_sku';
		$arrCode[] = 'd_brand'; 
		$arrCode[] = 'special_price';
		
		$attributeArr = $this->getAttributeArr($arrCode, $product->getId());
		
		if(Mage::helper('advanceseo/meta')->isEnableMetaTitle()){
			$title = '';
			$strTemplate = Mage::helper('advanceseo/meta')->getTemplateMetaTitle();
			if($strTemplate != ''){
				$arrTemplate = Mage::helper('advanceseo/data')->getArrFromTemplate($strTemplate);
				$title = Mage::helper('advanceseo/data')->getStrFromTemplate($arrTemplate, $attributeArr, $strTemplate);
			}	
			return $title;				
		}
	}
	public function getProductDesc($product)
	{
		if(Mage::helper('advanceseo/meta')->isEnableMetaDescription()){
				$arrCode[] = 'name';
				$arrCode[] = 'website';
				$arrCode[] = 'supplier_sku';
				$arrCode[] = 'description';
				$arrCode[] = 'short_description';
				$arrCode[] = 'd_brand'; 
				$arrCode[] = 'special_price';
				
				$desc	   = '';
            	$attributeArr = $this->getAttributeArr($arrCode, $product->getId());
            	$productMeta = Mage::helper('advanceseo/meta')->getTemplateMetaDescription();
				
            	$arrTemplate = Mage::helper('advanceseo/data')->getArrFromTemplate($productMeta);
            	$desc = Mage::helper('advanceseo/data')->getStrFromTemplate($arrTemplate, $attributeArr, $productMeta);
				
				//Limit description
				$limit 	= Mage::helper('advanceseo/meta')->getWordRangeDescription();
				if($limit) {
					$desc		= Mage::helper('advanceseo/data')->limitContentByWord($desc, $limit);
				}
				
				return $desc;
        }
	}
	public function getProductKw($product)
	{
		if(Mage::helper('advanceseo/meta')->isEnableMetaKeyWord()){
				
			$collection = Mage::getResourceModel('eav/entity_attribute_collection')
            				->setEntityTypeFilter( Mage::getModel('eav/entity')->setType('catalog_product')->getTypeId() )
            				->addFilter("is_visible", 1)
            				->addFilter("is_filterable", 1);
							
			$arrCode = array();		
			
			foreach($collection->getItems() as $col) {
	            $arrCode[] = $col->getAttributeCode();
	        }
			
			$arrCode[] = 'name';
			
			$attributeArr = $this->getAttributeArr($arrCode, $product->getId());
				
			$strDescription = '';
			
			foreach($attributeArr as $key=>$value){
				if($key != 'price'){
					$strDescription	 .= ' ' . $value;
				}
			}
			
			$keyword = $strDescription;
			
			$arrWord = Mage::helper('core/string')->splitWords($strDescription);
			
			if(count($arrWord>1)){
				$keyword = Mage::helper('advanceseo/data')->splitTwoWords($arrWord);
			}
			//Limit word title
			if($limit 	= Mage::helper('advanceseo/meta')->getWordRangeTitle()) {
			   $limit 	= Mage::helper('advanceseo/meta')->getWordRangeTitle();
			}
			
			$keyword 	.= Mage::helper('advanceseo/data')->limitContentByWord($keyword, $limit);
			
			//Included Key Word
			$includedKeyWord = Mage::helper('advanceseo/meta')->getIncludedKeyWork();
			
			if(!empty($includedKeyWord)){
				$keyword .= ','. $includedKeyWord;
			}
			
			return $keyword;
		}
	}
	public function getAttributeArr($arrCode, $productId)
    {
			$attributes = Mage::getModel('catalog/product')
						  ->load($productId);
			$data = $attributes->getData();
			
			//Attribute code template product
			
			$attributeArray = array();
			
			foreach ($data as $key=>$value){
				
				if(in_array($key, $arrCode)){
					 
					$actualValue = $attributes->getResource()
								->getAttribute($key)
								->getSource()
								//->getFrontend()
								//->getValue($attributes);
								->getOptionText($value);
					
					if($key =='name')
					{
						$actualValue = $value;
					}
					
					if($key == 'description')
					{
						$actualValue = $value;
					}
					
					if($key == 'short_description')
					{
						$actualValue = $value;
					}
					
					if($key == 'price')
					{
						$actualValue = $value;
					}
					
					if($key == 'special_price')
					{
						$actualValue = $value;
					}
					
					if($key == 'supplier_sku')
					{
						$actualValue = $value;
					}
					
					if($actualValue!='No' || $actualValue !== NULL){
						$attributeArray[$key] = $actualValue;
					}
					
				}
			}
			
			return $attributeArray;
    }
	public function getProcessedStr($string) 
	{
		$str = $this->removeHtmlTag($string);
		return $this->getRewriteString($str);
	}
	public function getRewriteString($string) 
	{
		$string    = htmlentities($string);
		$string    = preg_replace("/&(.)(acute|cedil|circ|ring|tilde|uml);/", "$1", $string);
		//$string    = preg_replace("/([^a-z0-9]+)/", "-", html_entity_decode($string));
		$string    = trim($string, "-");
		$string    = strtr($string,
					 "\xe1\xc1\xe0\xc0\xe2\xc2\xe4\xc4\xe3\xc3\xe5\xc5".
					 "\xaa\xe7\xc7\xe9\xc9\xe8\xc8\xea\xca\xeb\xcb\xed".
					 "\xcd\xec\xcc\xee\xce\xef\xcf\xf1\xd1\xf3\xd3\xf2".
					 "\xd2\xf4\xd4\xf6\xd6\xf5\xd5\x8\xd8\xba\xf0\xfa\xda".
					 "\xf9\xd9\xfb\xdb\xfc\xdc\xfd\xdd\xff\xe6\xc6\xdf\xf8",
					 "aAaAaAaAaAaAacCeEeEeEeEiIiIiIiInNo".
					 "OoOoOoOoOoOoouUuUuUuUyYyaAso");
		return $string;
	}
	public function getStrWordsExcluded($str)
	{
		
		$strExclude = Mage::helper('advanceseo/meta')->getWordsExclude();
		if(empty($strExclude) || empty($str)){
			return;
		}
		
		$arrWordExclude = explode(',', $strExclude);
		foreach($arrWordExclude as $word){
			$word = trim($word);
			$str= preg_replace("#($word)#imsU", '', $str);	
		}
		return $str;
		
	}
	public function getKeywordProcessed($productTitle , $productName=null)
	{
		$strTitle = '';
		if($productName!=null){
			$strTitle.= $this->getStrWordsExcluded($productName);
		}
		
		$productTitle = $this->getStrWordsExcluded($productTitle);
		
		$arrNumberExclude = explode(',', Mage::helper('advanceseo/meta')->getJumpNumber());
		
		$this->getStrExploded($arrNumberExclude, $productTitle, &$newStr);
		
		$strTitle .= $newStr;
		return trim($strTitle, ',');
	}
	public function countWords($str)
	{
		$str = trim($str);
        $count=1;
        for($i=0; $i<strlen($str); $i++){
        	if(($str[$i]==" ") && ($str[$i+1] != " ")){
                $count++;
            }
        }
       	return $count;
	}
	public function subStrByWord($str, $limit)
	{
		$str = trim($str);
        $count=1;
        for($i=0; $i<strlen($str); $i++){
        	if(($str[$i]==" ") && ($str[$i+1] != " ")){
                $count++;
            }
            if($count == ($limit+1)){
				$len = strlen($str) - strlen(substr($str,0, $i));
				$newStr = substr($str,$i, $len);
				break;
            }
        }
		
       	return $newStr;
	}
	public function getStrExploded($arrNumberExclude, $string, &$newStr)
	{
		//HTC Touch Diamond Product Test Black
		
		foreach($arrNumberExclude as $key => $number){
		
			$numberWords = $this->countWords($string);
			
			$result = ($numberWords/$number);
			if($result>=1){
				for($i=0; $i<$result; $i++){
					$tmpStr = $this->limitContentByWord($string, $number);
					$newStr .= ','.$tmpStr;
					$string = $this->subStrByWord($string, $number);
				}
			}else{
				$newStr .= $this->limitContentByWord($string, $number);
				unset($arrNumberExclude[$key]);
				//echo $key;
				$this->getStrExploded($arrNumberExclude,$string, $newStr);
				
			}
		}
	}
}